package com.hfh.jdbc;

import com.mysql.jdbc.Driver;
import java.sql.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;



/**
 * @Author hfh
 * @Date 2022 09 17 22 09
 **/
public class JDBCTest {
    public static void main(String[] args) {

        //初始化登录的UI界面
        Map<String,String> map = initUI();
        //登录方法返回时候登录成功
        boolean loginSuccess = login(map);

        System.out.println(loginSuccess ? "登录成功" : "登录失败");

    }

    private static boolean login(Map<String, String> map) {
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;

        boolean loginSuccess = false;
//        String loginName = map.get("loginName");
//        String loginPwd = map.get("loginPwd");

        //sql注入
        String loginName = "fdsa";
        String loginPwd = "fdsa' or '1' = '1";

        try {
            //1、注册驱动
//            Class.forName("com.mysql.jdbc.Driver");
            Class.forName("com.mysql.jdbc.Driver");
            //2、建立连接
            String url = "jdbc:mysql://localhost:3306/poetry";
            String user = "root";
            String password = "123456";
            conn = DriverManager.getConnection(url,user,password);
            //3、连接数据库对象
            stmt = conn.createStatement();
            //4、sql语句
            String sql = "select * from logininfo where loginName = '"+loginName
                    +"' and loginPwd = '"+loginPwd+"'";
            //5、操作返回数据集
            rs = stmt.executeQuery(sql);
            if (rs.next()){
                loginSuccess = true;
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            //6、关闭资源
            if(rs!=null){
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(stmt!=null){
                try {
                    stmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(conn!=null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        return loginSuccess;
    }

    private static Map<String, String> initUI() {
        Scanner scan = new Scanner(System.in);
        System.out.println("请输入登录名：");
        String loginName = scan.nextLine();
        System.out.println("请输入密码：");
        String loginPwd = scan.nextLine();
        Map<String,String> map = new HashMap<>();
        map.put("loginName",loginName);
        map.put("loginPwd",loginPwd);
        return map;
    }
}
